package com.itibo.common;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import com.itibo.models.ByteDocument;
import com.itibo.models.CSVDocument;
import com.itibo.models.Document;
import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

@ManagedBean
@RequestScoped
public class UploadBean {
    @ManagedProperty(value = "#{songsBean}")
    private SongsBean songsBean;
    private UploadedFile uploadedFile;

    public void submit() throws IOException {
        String fileName = FilenameUtils.getName(uploadedFile.getName());
        String contentType = uploadedFile.getContentType();
        byte[] bytes = uploadedFile.getBytes();
        Document doc = new CSVDocument(bytes);
        songsBean.processDocument(doc);
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(String.format("File '%s' of type '%s' successfully uploaded!", fileName, contentType)));
    }

    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }

    public SongsBean getSongsBean() {
        return songsBean;
    }

    public void setSongsBean(SongsBean songsBean) {
        this.songsBean = songsBean;
    }
}